//
//  NewsSearchViewController.m
//  ShowYork
//
//  Created by hxh on 2021/5/11.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "NewsSearchViewController.h"
#import "CommonWebViewController.h"
#import "NewsListSearchView.h"
#import "NewsListItemModel.h"
#import "NewsSearchResultCell.h"
#import "NewsListItemCell.h"
@interface NewsSearchViewController ()<UITableViewDelegate,UITableViewDataSource,NewsListSearchViewDelegate,NewsSearchResultCellDelegate,NewsListItemCellDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSMutableArray *resultArray;
@property (nonatomic,strong)NewsListSearchView *searchView;
@property (nonatomic,strong)UILabel *noDataLb;
@property (nonatomic,copy)NSString *searchKey;

@property (nonatomic,assign)BOOL isResult;

@property (nonatomic,strong)NSURLSessionTask *task;

@end

@implementation NewsSearchViewController


- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)resultArray{
    if (!_resultArray) {
        _resultArray = [NSMutableArray array];
    }
    return _resultArray;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;
    [IQKeyboardManager sharedManager].enable = NO;

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;
    [IQKeyboardManager sharedManager].enable = YES;
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
}

- (void)setUI{
    
    self.isHideNavBar = YES;
    
    self.searchView = [[NewsListSearchView alloc]init];
    self.searchView.delegate = self;
    [self.view addSubview:self.searchView];
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.height.mas_equalTo(44);
    }];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
    }];
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    self.tableView.mj_footer = footer;
    
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    self.noDataLb = [[UILabel alloc]init];
    self.noDataLb.text = @"无内容";
    self.noDataLb.textColor = C153;
    self.noDataLb.font = font(12);
    self.noDataLb.hidden = YES;
    
    [self.view addSubview:self.noDataLb];
    
    [self.noDataLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view).offset(-100);
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isResult) {
        return self.resultArray.count;
    }else{
        return self.dataArray.count;
    }
 
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (self.isResult) {
        NewsListItemCell *cell = [NewsListItemCell cellWithTableView:tableView];
        cell.delegate = self;
        [cell setItemModel:self.resultArray[indexPath.row]];
        return cell;
    }else{
        NewsSearchResultCell *cell = [NewsSearchResultCell cellWithTableView:tableView];
        cell.delegate = self;
        [cell setItemModel:self.dataArray[indexPath.row]];
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isResult) {
        return UITableViewAutomaticDimension;
    }else{
        return 50.0f;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}
#pragma mark - NewsSearchResultCellDelegate
- (void)showNewsSearchResultByCurrentModel:(NewsListItemModel *)currentModel{
    
    [self.view endEditing:YES];
    
    self.searchKey = currentModel.title;
    
    self.isResult = YES;
    // 刷新数据源
    [self loadDataSource];
    
}
- (void)showNewsDetailByCurrentModel:(NewsListItemModel *)itemModel{
    CommonWebViewController *dtlVC = [[CommonWebViewController alloc]init];
    dtlVC.webUrl = [NSString stringWithFormat:@"%@lesson/news/%@?isApp=true",HtmlUrl,itemModel.id];
    dtlVC.isDark = NO;
    [self.navigationController pushViewController:dtlVC animated:YES];
}



#pragma mark - NewsListSearchViewDelegate
- (void)cancel{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)textChange:(NSString *)text{
 
    self.noDataLb.hidden = YES;
    self.tableView.mj_footer.hidden = YES;
    self.isResult = NO;
    
    [self.resultArray removeAllObjects];
    
    if ([text cl_removeSpaceString].length != 0) {
        self.searchKey = text;
        [self loadDataSource];
    }else{
        self.searchKey = @"";
        [self.dataArray removeAllObjects];
        [self.tableView reloadData];
    }
}
- (void)textSearch:(NSString *)text{
   
    [self.view endEditing:YES];
    
    self.isResult = YES;
    self.noDataLb.hidden = YES;
    self.tableView.mj_footer.hidden = YES;

    [self.resultArray removeAllObjects];
    
    if ([text cl_removeSpaceString].length != 0) {
        self.searchKey = text;
        [self loadDataSource];
    }
}
-(void)textSpace{
    
    self.searchKey = @"";
    self.isResult = NO;
    self.noDataLb.hidden = YES;
    self.tableView.mj_footer.hidden = YES;
    [self.resultArray removeAllObjects];
    [self.dataArray removeAllObjects];
    [self.tableView reloadData];
}

#pragma mark - loadData
- (void)loadDataSource{
    
    self.tableView.mj_footer.hidden = YES;
    
    [self.task cancel];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetNewsByTitle];
    param[@"title"] = self.searchKey;
    param[@"pageIndex"] = @(1);
    param[@"pageSize"] = @(9999);
    self.task = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetNewsByTitle) parames:param success:^(id responseObj) {
        
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
       
        if (self.isResult) {
            self.resultArray = [NewsListItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
            self.noDataLb.hidden = self.resultArray.count > 0;
            self.tableView.mj_footer.hidden = self.resultArray.count == 0;
            CGFloat bottom = self.tableView.mj_insetB;
            if (self.tableView.mj_footer.cl_height == 44.0f) {
                self.tableView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.tableView.mj_insetB = 138.0f;
                }
            }
        }else{
            self.dataArray = [NewsListItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
            self.noDataLb.hidden = self.dataArray.count > 0;
            self.tableView.mj_footer.hidden = YES;
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

#pragma mark - other
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

@end
